<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>账户管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#6366F1',
                        neutral: {
                            50: '#F9FAFB',
                            100: '#F3F4F6',
                            200: '#E5E7EB',
                            700: '#374151',
                            800: '#1F2937',
                            900: '#111827'
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5;
            }
            .table-hover-row {
                @apply hover:bg-neutral-50 transition-colors;
            }
            .alert-enter {
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-neutral-50 to-neutral-100 min-h-screen font-sans text-neutral-800">
<!-- 顶部导航 -->
<header class="bg-white/80 backdrop-blur-sm shadow-sm sticky top-0 z-10">
    <div class="max-w-6xl mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-user-circle-o text-primary text-xl"></i>
            <h1 class="text-lg font-semibold text-neutral-800">账户管理</h1>
        </div>
        <div class="flex items-center gap-4">
            <span class="text-sm text-neutral-600 hidden md:inline-flex items-center gap-1" id="currentUserInfo">
                <i class="fa fa-user"></i>
                <span>加载中...</span>
            </span>
            <a href="/api/chat" class="text-neutral-700 hover:text-primary transition-colors flex items-center gap-1 px-3 py-1.5 rounded-md hover:bg-neutral-100">
                <i class="fa fa-comments"></i>
                <span>返回聊天</span>
            </a>
            <a href="/api/logout" class="text-neutral-700 hover:text-primary transition-colors flex items-center gap-1 px-3 py-1.5 rounded-md hover:bg-neutral-100">
                <i class="fa fa-sign-out"></i>
                <span>退出登录</span>
            </a>
        </div>
    </div>
</header>

<main class="max-w-6xl mx-auto p-4 md:p-6 lg:p-8">
    <!-- 状态消息 -->
    <div id="successMsg" class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md mb-6 flex items-center gap-2 hidden alert-enter">
        <i class="fa fa-check-circle"></i>
        <span></span>
    </div>
    <div id="errorMsg" class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md mb-6 flex items-center gap-2 hidden alert-enter">
        <i class="fa fa-exclamation-circle"></i>
        <span></span>
    </div>

    <!-- 账户管理卡片 -->
    <div class="bg-white rounded-2xl shadow-md overflow-hidden mb-6">
        <!-- 卡片标题区 -->
        <div class="bg-gradient-to-r from-primary to-secondary px-6 py-4">
            <h2 class="text-xl font-bold text-white" id="cardTitle">
                加载中...
            </h2>
            <p class="text-white/90 text-sm mt-1" id="cardSubtitle">
                加载中...
            </p>
        </div>

        <!-- 管理员功能区 -->
        <div id="adminSection" class="p-6 hidden">
            <!-- 操作按钮 -->
            <div class="flex flex-wrap justify-between items-center mb-6 gap-4">
                <div>
                    <h3 class="text-lg font-semibold">用户列表</h3>
                    <p class="text-sm text-neutral-500">共 <span id="userCount">0</span> 个用户</p>
                </div>
                <button id="addUserBtn" class="bg-primary hover:bg-primary/90 text-white px-5 py-2 rounded-lg btn-hover flex items-center gap-2">
                    <i class="fa fa-plus"></i>
                    <span>添加用户</span>
                </button>
            </div>

            <!-- 用户表格 -->
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-neutral-200">
                    <thead>
                    <tr>
                        <th class="px-4 py-3 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">ID</th>
                        <th class="px-4 py-3 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">用户名</th>
                        <th class="px-4 py-3 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">角色</th>
                        <th class="px-4 py-3 bg-neutral-50 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-neutral-200" id="userTableBody">
                    <tr>
                        <td colspan="5" class="px-4 py-8 text-center text-neutral-500">
                            <i class="fa fa-spinner fa-spin mr-2"></i>加载用户数据中...
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 普通用户功能区 -->
        <div id="userSection" class="p-6 hidden">
            <div class="max-w-md mx-auto">
                <h3 class="text-lg font-semibold mb-4">个人资料</h3>

                <form id="userProfileForm" class="space-y-4">
                    <input type="hidden" id="userId" name="id">

                    <div>
                        <label for="username" class="block text-sm font-medium text-neutral-700 mb-1">用户名</label>
                        <input type="text" id="username" name="username"
                               class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors"
                               required minlength="3" maxlength="20">
                    </div>

                    <div>
                        <label for="oldPassword" class="block text-sm font-medium text-neutral-700 mb-1">原密码（修改密码时必填）</label>
                        <input type="password" id="oldPassword" name="oldPassword"
                               class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors">
                    </div>

                    <div>
                        <label for="newPassword" class="block text-sm font-medium text-neutral-700 mb-1">新密码（至少6个字符）</label>
                        <input type="password" id="newPassword" name="newPassword"
                               class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors"
                               minlength="6">
                    </div>

                    <div>
                        <label for="confirmPassword" class="block text-sm font-medium text-neutral-700 mb-1">确认新密码</label>
                        <input type="password" id="confirmPassword" name="confirmPassword"
                               class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors"
                               minlength="6">
                    </div>

                    <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg btn-hover">
                        保存修改
                    </button>
                </form>
            </div>
        </div>
    </div>
</main>

<!-- 添加/编辑用户模态框 (仅管理员可见) -->
<div id="userModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-2xl shadow-lg w-full max-w-md mx-4 transform transition-all">
        <div class="px-6 py-4 border-b border-neutral-200 flex justify-between items-center">
            <h3 id="modalTitle" class="text-lg font-semibold">添加用户</h3>
            <button id="closeModalBtn" class="text-neutral-500 hover:text-neutral-700">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-6">
            <form id="userForm" class="space-y-4">
                <input type="hidden" id="modalUserId" name="id">

                <div>
                    <label for="modalUsername" class="block text-sm font-medium text-neutral-700 mb-1">用户名</label>
                    <input type="text" id="modalUsername" name="username"
                           class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors"
                           required minlength="3" maxlength="20">
                </div>

                <div>
                    <label for="modalPassword" class="block text-sm font-medium text-neutral-700 mb-1">密码</label>
                    <input type="password" id="modalPassword" name="password"
                           class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors"
                           required minlength="6">
                </div>

                <div>
                    <label for="modalRole" class="block text-sm font-medium text-neutral-700 mb-1">角色</label>
                    <select id="modalRole" name="role"
                            class="w-full px-4 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors">
                        <option value="user">普通用户</option>
                        <option value="admin">管理员</option>
                    </select>
                </div>

                <div class="pt-2">
                    <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg btn-hover">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 (仅管理员可见) -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-2xl shadow-lg w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-neutral-200">
            <h3 class="text-lg font-semibold">确认删除</h3>
        </div>
        <div class="p-6">
            <p class="text-neutral-700 mb-6">
                确定要删除用户 <span id="deleteUsername" class="font-medium"></span> 吗？此操作不可撤销。
            </p>
            <div class="flex gap-3">
                <button id="cancelDeleteBtn" class="flex-1 px-4 py-2 border border-neutral-300 rounded-lg hover:bg-neutral-50 transition-colors">
                    取消
                </button>
                <button id="confirmDeleteBtn" class="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                    确认删除
                </button>
            </div>
            <input type="hidden" id="deleteUserId">
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentUser = null;
    const token = localStorage.getItem('token');
    //const authHeaders = token ? { 'Authorization': `Bearer ${token}` } : {};

    // 工具函数 - 显示消息
    function showMessage(elementId, text, duration = 3000) {
        const element = document.getElementById(elementId);
        element.querySelector('span').textContent = text;
        element.classList.remove('hidden');

        if (duration) {
            setTimeout(() => {
                element.classList.add('hidden');
            }, duration);
        }
    }

    // 隐藏所有消息
    function hideAllMessages() {
        document.getElementById('successMsg').classList.add('hidden');
        document.getElementById('errorMsg').classList.add('hidden');
    }

    // 获取当前用户信息
    async function getCurrentUser(token) {
        try {
            const response = await fetch('/api/currentUser', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                }
            });

            if (!response.ok) {
                throw new Error('获取用户信息失败');
            }
            const currentUserData = await response.json();
            currentUser = currentUserData.data;

            updateUIForCurrentUser();

            return currentUser;
        } catch (error) {
            showMessage('errorMsg', error.message);
            console.error('获取当前用户失败:', error);
            // 若获取用户失败，可能是未登录，重定向到登录页
            setTimeout(() => window.location.href = '/api/login', 2000);
        }
    }

    // 根据当前用户角色更新UI
    function updateUIForCurrentUser() {
        if (!currentUser) return;

        // 更新顶部用户信息
        const userRoleLabel = currentUser.role === 'admin'
            ? '<span class="bg-primary/10 text-primary text-xs px-2 py-0.5 rounded-full">管理员</span>'
            : '<span class="bg-neutral-200 text-neutral-700 text-xs px-2 py-0.5 rounded-full">普通用户</span>';

        document.getElementById('currentUserInfo').innerHTML = `
            <i class="fa fa-user"></i>
            <span>${currentUser.username}</span>
            ${userRoleLabel}
        `;

        // 更新卡片标题
        if (currentUser.role === 'admin') {
            document.getElementById('cardTitle').textContent = '用户管理';
            document.getElementById('cardSubtitle').textContent = '管理系统中的所有用户账户';
            document.getElementById('adminSection').classList.remove('hidden');
            loadAllUsers();
        } else {
            document.getElementById('cardTitle').textContent = '个人信息';
            document.getElementById('cardSubtitle').textContent = '查看和修改您的个人信息';
            document.getElementById('userSection').classList.remove('hidden');
            // 填充个人资料表单
            document.getElementById('userId').value = currentUser.id;
            document.getElementById('username').value = currentUser.username;
        }
    }

    // 管理员加载所有用户
    async function loadAllUsers() {
        try {
            const response = await fetch('/api/admin/list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                }
            });

            if (!response.ok) {
                throw new Error('获取用户列表失败');
            }

            const users = await response.json();
            updateUserTable(users);
        } catch (error) {
            showMessage('errorMsg', error.message);
            console.error('加载用户列表失败:', error);
        }
    }

    // 更新用户表格
    function updateUserTable(users) {
        const tableBody = document.getElementById('userTableBody');
        document.getElementById('userCount').textContent = users.length;

        if (users.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="5" class="px-4 py-8 text-center text-neutral-500">
                        <i class="fa fa-info-circle mr-2"></i>没有用户数据
                    </td>
                </tr>
            `;
            return;
        }

        tableBody.innerHTML = '';
        users.forEach(user => {
            const row = document.createElement('tr');
            row.className = 'table-hover-row';

            // 格式化日期
            const createTime = user.createTime ? new Date(user.createTime).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            }) : 'N/A';

            row.innerHTML = `
                <td class="px-4 py-3 whitespace-nowrap text-sm text-neutral-700">${user.id}</td>
                <td class="px-4 py-3 whitespace-nowrap text-sm text-neutral-700">${user.username}</td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="${user.role === 'admin' ? 'bg-primary/10 text-primary' : 'bg-neutral-200 text-neutral-700'} text-xs px-2 py-1 rounded-full">
                        ${user.role === 'admin' ? '管理员' : '普通用户'}
                    </span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap text-sm text-neutral-500">${createTime}</td>
                <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                    <div class="flex gap-2">
                        <button data-id="${user.id}" data-username="${user.username}" data-role="${user.role}"
                                class="text-primary hover:text-primary/80 edit-user-btn">
                            <i class="fa fa-pencil"></i> 编辑
                        </button>
                        <button data-id="${user.id}" data-username="${user.username}"
                                class="text-red-500 hover:text-red-600 delete-user-btn">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </div>
                </td>
            `;
            tableBody.appendChild(row);
        });

        // 绑定编辑和删除按钮事件
        bindEditAndDeleteEvents();
    }

    // 绑定编辑和删除按钮事件
    function bindEditAndDeleteEvents() {
        // 编辑用户
        document.querySelectorAll('.edit-user-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');
                const role = this.getAttribute('data-role');

                document.getElementById('modalTitle').textContent = '编辑用户';
                document.getElementById('modalUserId').value = id;
                document.getElementById('modalUsername').value = username;
                document.getElementById('modalRole').value = role;
                // 编辑时密码非必填
                document.getElementById('modalPassword').required = false;
                document.getElementById('modalPassword').placeholder = '不修改请留空';
                document.getElementById('userModal').classList.remove('hidden');
            });
        });

        // 删除用户
        document.querySelectorAll('.delete-user-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');

                document.getElementById('deleteUserId').value = id;
                document.getElementById('deleteUsername').textContent = username;
                document.getElementById('deleteModal').classList.remove('hidden');
            });
        });
    }

    // 保存用户（添加或编辑）
    async function saveUser(event) {
        event.preventDefault();

        const userId = document.getElementById('modalUserId').value;
        const userData = {
            username: document.getElementById('modalUsername').value,
            password: document.getElementById('modalPassword').value,
            role: document.getElementById('modalRole').value
        };

        // 如果是编辑且密码为空，则不发送密码字段
        if (userId && !userData.password) {
            delete userData.password;
        }

        try {
            let url = '/api/admin/add';
            let method = 'POST';

            // 如果有用户ID，则是编辑操作
            if (userId) {
                url = `/api/admin/update`;
                method = 'PUT';
                userData.id = userId;
            }

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Authorization': token,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            if (!response.ok) {
                const error = await response.text();
                throw new Error(error || '保存用户失败');
            }

            // 关闭模态框并刷新用户列表
            document.getElementById('userModal').classList.add('hidden');
            await loadAllUsers();
            showMessage('successMsg', userId ? '用户更新成功' : '用户添加成功');
        } catch (error) {
            showMessage('errorMsg', error.message);
            console.error('保存用户失败:', error);
        }
    }

    // 删除用户
    async function deleteUser() {
        const userId = document.getElementById('deleteUserId').value;

        if (!userId) {
            showMessage('errorMsg', '用户ID不存在');
            return;
        }

        try {
            const response = await fetch(`/api/admin/delete/${userId}`, {
                method: 'DELETE',
                headers:  {
                    'Authorization': token,
                    'Accept': 'application/json'
                },
            });

            if (!response.ok) {
                throw new Error('删除用户失败');
            }

            // 关闭模态框并刷新用户列表
            document.getElementById('deleteModal').classList.add('hidden');
            loadAllUsers();
            showMessage('successMsg', '用户删除成功');
        } catch (error) {
            showMessage('errorMsg', error.message);
            console.error('删除用户失败:', error);
        }
    }

    // 更新个人信息
    async function updateProfile(event) {
        event.preventDefault();

        const userId = document.getElementById('userId').value;
        const username = document.getElementById('username').value;
        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        // 前端验证
        if (newPassword) {
            if (!oldPassword) {
                showMessage('errorMsg', '请输入原密码');
                return;
            }

            if (newPassword !== confirmPassword) {
                showMessage('errorMsg', '新密码和确认密码不匹配');
                return;
            }
        }

        const userData = {
            id: userId,
            username: username,
            oldPassword: oldPassword,
            newPassword: newPassword
        };

        try {
            const response = await fetch('/api/account/update', {
                method: 'PUT',
                headers: {...authHeaders, 'Content-Type': 'application/json'},
                body: JSON.stringify(userData)
            });

            if (!response.ok) {
                const error = await response.text();
                throw new Error(error || '更新个人信息失败');
            }

            // 刷新当前用户信息
            await getCurrentUser();
            showMessage('successMsg', '个人信息更新成功');

            // 清空密码字段
            document.getElementById('oldPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        } catch (error) {
            showMessage('errorMsg', error.message);
            console.error('更新个人信息失败:', error);
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 获取当前用户信息
        getCurrentUser(token);

        // 模态框控制
        document.getElementById('addUserBtn')?.addEventListener('click', function() {
            document.getElementById('modalTitle').textContent = '添加用户';
            document.getElementById('userForm').reset();
            document.getElementById('modalUserId').value = '';
            document.getElementById('modalPassword').required = true;
            document.getElementById('modalPassword').placeholder = '';
            document.getElementById('userModal').classList.remove('hidden');
        });

        document.getElementById('closeModalBtn')?.addEventListener('click', function() {
            document.getElementById('userModal').classList.add('hidden');
        });

        document.getElementById('cancelDeleteBtn')?.addEventListener('click', function() {
            document.getElementById('deleteModal').classList.add('hidden');
        });

        document.getElementById('confirmDeleteBtn')?.addEventListener('click', deleteUser);

        // 表单提交事件
        document.getElementById('userForm')?.addEventListener('submit', saveUser);
        document.getElementById('userProfileForm')?.addEventListener('submit', updateProfile);

        // 点击模态框外部关闭
        document.getElementById('userModal')?.addEventListener('click', function(e) {
            if (e.target === this) this.classList.add('hidden');
        });

        document.getElementById('deleteModal')?.addEventListener('click', function(e) {
            if (e.target === this) this.classList.add('hidden');
        });

        // 关闭消息提示
        document.querySelectorAll('#successMsg, #errorMsg').forEach(el => {
            el.addEventListener('click', function() {
                this.classList.add('hidden');
            });
        });
    });
</script>
</body>
</html>
